home *** CD-ROM | disk | FTP | other *** search
/ MacHack 1994 / MacHack 1994.toast / MacHack™ 1987-1994 / MacHack™ '90 / MacHack'90 Proceedings / John Norstad / Reusable Code / Source / utl.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-06-10  |  50.3 KB  |  1,707 lines  |  [TEXT/MPS ]

  1. /*______________________________________________________________________
  2.  
  3.     utl.c - Utilities.
  4.     
  5.     Copyright © 1988, 1989, 1990 Northwestern University.  Permission is 
  6.     granted to use this code in your own projects, provided you give credit 
  7.     to both John Norstad and Northwestern University in your about box or 
  8.     document.
  9.     
  10.     This module exports miscellaneous reusable utility routines.
  11. _____________________________________________________________________*/
  12.  
  13.  
  14. #pragma load "precompile"
  15. #include "utl.h"
  16.  
  17. #pragma segment utl
  18.  
  19.  
  20. /*______________________________________________________________________
  21.  
  22.     Global Variables.
  23. _____________________________________________________________________*/
  24.  
  25.  
  26. static SysEnvRec        TheWorld;        /* system environment record */
  27. static Boolean            GotSysEnviron = false;    
  28.                                                 /* true if sys environ has been
  29.                                                     gotten */
  30.     
  31.             
  32. static CursHandle     *CursArray;        /* ptr to array of cursor handles */
  33. static short             NumCurs;            /* number of cursors to rotate */
  34. static short             TickInterval;    /* number of ticks between rotations */
  35. static short             CurCurs;            /* index of current cursor */
  36. static short             LastTick;        /* tick count at loast rotation */
  37.  
  38. static ModalFilterProcPtr    Filter;    /* dialog filter proc */
  39. static short            CancelItem;        /* item number of cancel button */
  40.  
  41. /*______________________________________________________________________
  42.  
  43.     GetSysEnvirons - Get System Environment.
  44.     
  45.     Exit:        global variable TheWorld = system environment record.
  46.                 global variable GotSysEnviron = true.
  47. _____________________________________________________________________*/
  48.  
  49.  
  50. static void GetSysEnvirons (void)
  51.  
  52. {
  53.     if (!GotSysEnviron) {
  54.         (void) SysEnvirons(curSysEnvVers, &TheWorld);
  55.         GotSysEnviron = true;
  56.     };
  57. }
  58.  
  59. /*______________________________________________________________________
  60.  
  61.     utl_PlotSmallIcon - Draw a small icon.
  62.     
  63.     Entry:    theRect = rectangle in which to draw the small icon.
  64.                 theHandle = handle to small icon.
  65.                     
  66.     For best results, the rectangle should be exactly 16 pixels square.
  67. _____________________________________________________________________*/
  68.  
  69.  
  70. void utl_PlotSmallIcon (Rect *theRect, Handle theHandle)
  71.  
  72. {
  73.     BitMap        srcBits;            /* Source bitmap for CopyBits */
  74.     
  75.     MoveHHi(theHandle);
  76.     HLock(theHandle);
  77.     srcBits.baseAddr = *theHandle;
  78.     srcBits.rowBytes = 2;
  79.     SetRect(&srcBits.bounds, 0, 0, 16, 16);
  80.     CopyBits(&srcBits, &qd.thePort->portBits, &srcBits.bounds, theRect,
  81.         srcCopy, nil);
  82.     HUnlock(theHandle);
  83. }
  84.  
  85. /*______________________________________________________________________
  86.  
  87.     utl_GetApplVol - Get the volume reference number of the application volume.
  88.     
  89.     Exit:        function result = volume reference number of the volume 
  90.                     containing the current application.
  91. _____________________________________________________________________*/
  92.  
  93.  
  94. short utl_GetApplVol (void)
  95.  
  96. {
  97.     short            vRefNum;                /* vol ref num */
  98.  
  99.     GetVRefNum(*(short*)(CurMap), &vRefNum);
  100.     return vRefNum;
  101. }
  102.  
  103. /*______________________________________________________________________
  104.  
  105.     utl_GetSysVol - Get the volume reference number of the system volume.
  106.     
  107.     Exit:        function result = volume reference number of the volume 
  108.                     containing the currently active system file.
  109. _____________________________________________________________________*/
  110.  
  111.  
  112. short utl_GetSysVol (void)
  113.  
  114. {
  115.     
  116.     short            vRefNum;                /* vol ref num */
  117.  
  118.     GetVRefNum(*(short*)(SysMap), &vRefNum);
  119.     return vRefNum;
  120. }
  121.  
  122. /*______________________________________________________________________
  123.  
  124.     utl_GetBlessedWDRefNum - Get the working directory reference number of
  125.         the Blessed Folder.
  126.     
  127.     
  128.     Exit:        function result = wdRefNum of blessed folder
  129. _____________________________________________________________________*/
  130.  
  131.  
  132. short utl_GetBlessedWDRefNum (void)
  133.  
  134. {
  135.     if (!GotSysEnviron) GetSysEnvirons();
  136.     return TheWorld.sysVRefNum;
  137. }
  138.  
  139. /*______________________________________________________________________
  140.  
  141.     utl_GetVolFilCnt - Get the number of files on a volume.
  142.     
  143.     Entry:    volRefNum = volume reference number of volume.
  144.     
  145.     Exit:        function result = number of files on volume.
  146.     
  147.     For serdver volumes this function always returns 0.
  148. _____________________________________________________________________*/
  149.  
  150.  
  151. long utl_GetVolFilCnt (short volRefNum)
  152.  
  153. {
  154.     HParamBlockRec        pBlock;        /* param block for PHBGetVInfo */
  155.     
  156.     pBlock.volumeParam.ioNamePtr = nil;
  157.     pBlock.volumeParam.ioVRefNum = volRefNum;
  158.     pBlock.volumeParam.ioVolIndex = 0;
  159.     (void) PBHGetVInfo(&pBlock, false);
  160.     return pBlock.volumeParam.ioVFilCnt;
  161. }
  162.  
  163. /*______________________________________________________________________
  164.  
  165.     utl_GetMBarHeight - Get Menu Bar Height
  166.     
  167.     Exit:        function result = menu bar height.
  168.     
  169.     See TN 117.
  170. _____________________________________________________________________*/
  171.  
  172.  
  173. short utl_GetMBarHeight (void)
  174.  
  175. {
  176.     static short        mBHeight = 0;
  177.     
  178.     if (!mBHeight) {
  179.         mBHeight = utl_Rom64() ? 20 : *(short*)MBarHeight;
  180.     };
  181.     return mBHeight;
  182. }
  183.  
  184. /*______________________________________________________________________
  185.  
  186.     utl_HaveColor - Determine if system has color QuickDraw.
  187.  
  188.     Exit:        function result = true if we have color QD.
  189. _____________________________________________________________________*/
  190.  
  191.  
  192. Boolean utl_HaveColor (void)
  193.  
  194. {
  195.     if (!GotSysEnviron) GetSysEnvirons();
  196.     return TheWorld.hasColorQD;
  197. }
  198.  
  199. /*______________________________________________________________________
  200.  
  201.     utl_GetWindGD - Get the GDevice containing a window.
  202.     
  203.     Entry:    theWindow = pointer to window.
  204.     
  205.     Exit:        gd = handle to GDevice, or nil if no color QD.
  206.                 screenRect = bounding rectangle of GDevice, or 
  207.                     qd.screenBits.bounds if no color QD.
  208.                 windRect = content rectangle of window, in global
  209.                     coords.
  210.                 hasMB = true if this screen contains the menu bar.
  211.                 
  212.     The routine determines the GDevice (screen) containing the maximum
  213.     intersection with a window.  See TN 79.
  214. _____________________________________________________________________*/
  215.  
  216.  
  217. void utl_GetWindGD (WindowPtr theWindow, GDHandle *gd, 
  218.     Rect *screenRect, Rect *windRect, Boolean *hasMB)
  219.     
  220. {
  221.     GrafPtr            savePort;            /* saved grafport */
  222.     Rect                sectRect;            /* intersection rect */
  223.     GDHandle            curDevice;            /* current GDevice */
  224.     GDHandle            dominantDevice;    /* dominant GDevice */
  225.     long                sectArea;            /* intersection area */
  226.     long                maxArea;                /* max intersection area */
  227.     
  228.     *windRect = theWindow->portRect;
  229.     if (utl_HaveColor()) {
  230.         GetPort(&savePort);
  231.         SetPort(theWindow);
  232.         LocalToGlobal((Point*)&windRect->top);
  233.         LocalToGlobal((Point*)&windRect->bottom);
  234.         windRect->top -= titleBarHeight;
  235.         curDevice = GetDeviceList();
  236.         maxArea = 0;
  237.         dominantDevice = nil;
  238.         while (curDevice) {
  239.             if (TestDeviceAttribute(curDevice, screenDevice) &&
  240.                 TestDeviceAttribute(curDevice, screenActive)) {
  241.                 SectRect(windRect, &(**curDevice).gdRect, §Rect);
  242.                 sectArea = (long)(sectRect.right - sectRect.left) * 
  243.                     (long)(sectRect.bottom - sectRect.top);
  244.                 if (sectArea > maxArea) {
  245.                     maxArea = sectArea;
  246.                     dominantDevice = curDevice;
  247.                 };
  248.             };
  249.             curDevice = GetNextDevice(curDevice);
  250.         };
  251.         windRect->top += titleBarHeight;
  252.         if (dominantDevice) {
  253.             *gd = dominantDevice;
  254.             *screenRect = (**dominantDevice).gdRect;
  255.             *hasMB = dominantDevice == GetMainDevice();
  256.         } else {
  257.             *gd = nil;
  258.             *screenRect = qd.screenBits.bounds;
  259.             *hasMB = true;
  260.         };    
  261.         SetPort(savePort);
  262.     } else {
  263.         *gd = nil;
  264.         *screenRect = qd.screenBits.bounds;
  265.         *hasMB = true;
  266.     };
  267. }
  268.  
  269. /*______________________________________________________________________
  270.  
  271.     utl_CenterDlogRect - Center a dialog rectangle.
  272.     
  273.     Entry:    rect = rectangle.
  274.                 centerMain = true to center on main (menu bar) screen.
  275.                 centerMain = false to center on the screen containing
  276.                     the maximum intersection with the frontmost window.
  277.     
  278.     Exit:        rect = rectangle offset so that it is centered on
  279.                     the specified screen, with twice as much space below
  280.                     the rect as above.
  281.                     
  282.     See HIN 6.
  283. _____________________________________________________________________*/
  284.  
  285.  
  286. void utl_CenterDlogRect (Rect *rect, Boolean centerMain)
  287.  
  288. {
  289.     Rect        screenRect;            /* screen rectangle */
  290.     short        mBHeight;            /* menu bar height */
  291.     GDHandle    gd;                    /* gdevice */
  292.     Rect        windRect;            /* window rectangle */
  293.     Boolean    hasMB;                /* true if screen contains menu bar */
  294.  
  295.     mBHeight = utl_GetMBarHeight();
  296.     if (centerMain) {
  297.         screenRect = qd.screenBits.bounds;
  298.     } else {
  299.         utl_GetWindGD(FrontWindow(), &gd, &screenRect, &windRect, &hasMB);
  300.         if (!hasMB) mBHeight = 0;
  301.     };
  302.     OffsetRect(rect,
  303.         (screenRect.right + screenRect.left - rect->right - rect->left) >> 1,
  304.         (screenRect.bottom + ((screenRect.top + mBHeight - rect->top)<<1) - 
  305.             rect->bottom + 7) / 3);
  306. }
  307.  
  308. /*______________________________________________________________________
  309.  
  310.     utl_CenterRect - Center a rectangle on the main screen.
  311.     
  312.     Entry:    rect = rectangle.
  313.     
  314.     Exit:        rect = rectangle offset so that it is centered on
  315.                     the main screen.
  316. _____________________________________________________________________*/
  317.  
  318.  
  319. void utl_CenterRect (Rect *rect)
  320.  
  321. {
  322.     Rect        screenRect;            /* main screen rectangle */
  323.     short        mBHeight;            /* menu bar height */
  324.  
  325.     mBHeight = utl_GetMBarHeight();
  326.     screenRect = qd.screenBits.bounds;
  327.     OffsetRect(rect,
  328.         (screenRect.right + screenRect.left - rect->right - rect->left) >> 1,
  329.         (screenRect.bottom - screenRect.top + mBHeight - 
  330.             rect->bottom - rect->top) >> 1);
  331. }
  332.  
  333. /*______________________________________________________________________
  334.  
  335.     utl_StaggerWindow - Stagger a New Window
  336.     
  337.     Entry:    windRect = window portrect.
  338.                 initialOffset = intitial pixel offset of window from corner.
  339.                 offset = offset for subsequent staggered windows.
  340.     
  341.     Exit:        pos = window position.
  342.     
  343.     According to HIN 6, a new window should be positioned as follows:
  344.     "The first document window should be positioned in the upper-left corner
  345.     of the gray area of the main screen (the screen with the menu bar).
  346.     Each additional independent window should be staggered from the upper-left
  347.     corner of the screen that contains the largest portion of the
  348.     frontmost window."  Also, "When a window is used or closed, its original
  349.     position becomes available again.  The next window opened should use this
  350.     position.  Similarly, if a window is moved onto a previously available
  351.     position, that position becomes unavailable again."
  352.     
  353.     This routine implements these rules.  A position is considered to be
  354.     "unavailable" if some other window is within (offset+1)/2 pixels of the
  355.     position in both the vertical and horizontal directions.
  356.     
  357.     If all slots are occupied, the routine attempts to locate the first one
  358.     which is occupied by only one other window.  If this attempt fails, it
  359.     tries to locate one which is occupied by only two other windows, etc.
  360.     Thus, if the screen is filled with staggered windows, subsequent windows
  361.     will be staggered on top of the existing ones, forming a second "layer."
  362.     If this layer fills up, a third layer is started, etc.
  363. _____________________________________________________________________*/
  364.  
  365.  
  366. void utl_StaggerWindow (Rect *windRect, short initialOffset, short offset, 
  367.     Point *pos)
  368.  
  369. {
  370.     GrafPtr            savedPort;        /* saved grafport */
  371.     short                offsetDiv2;        /* offset/2 */
  372.     short                windHeight;        /* window height */
  373.     short                windWidth;        /* window width */
  374.     WindowPtr        frontWind;        /* pointer to front window */
  375.     GDHandle            gd;                /* GDevice */
  376.     Rect                screenRect;        /* screen rectangle */
  377.     Rect                junkRect;        /* window rectangle */
  378.     Boolean            hasMB;            /* true if screen has menu bar */
  379.     Point                initPos;            /* initial staggered window position */
  380.     Point                curPos;            /* current staggered window position */
  381.     WindowPtr        curWind;            /* pointer to current window */
  382.     Point                windPos;            /* current window position */
  383.     short                deltaH;            /* horizontal distance */
  384.     short                deltaV;            /* vertical distance */
  385.     short                layer;            /* layer number */
  386.     short                nOccupied;        /* number windows occupying cur pos */
  387.     
  388.     GetPort(&savedPort);
  389.     offsetDiv2 = (offset+1)>>1;
  390.     windHeight = windRect->bottom - windRect->top;
  391.     windWidth = windRect->right - windRect->left;
  392.     frontWind = FrontWindow();
  393.     if (frontWind) {
  394.         utl_GetWindGD(frontWind, &gd, &screenRect, &junkRect, &hasMB);
  395.     } else {
  396.         screenRect = qd.screenBits.bounds;
  397.         hasMB = true;
  398.     };
  399.     if (hasMB) screenRect.top += utl_GetMBarHeight();
  400.     SetPt(&initPos, screenRect.left + initialOffset + 1, 
  401.         screenRect.top + initialOffset + titleBarHeight);
  402.     layer = 1;
  403.     while (true) {
  404.         /* Test each layer number "layer", starting with 1 and incrementing by 1.
  405.             Break out of the loop when we find a position curPos which
  406.             is "occupied" by fewer than "layer" other windows. */
  407.         curPos = initPos;
  408.         while (true) {
  409.             /* Test each possible position curPos.  Break out of the loop
  410.                 when we have exhaused the possible positions, or when we
  411.                 have located one which has < layer "occupants". */
  412.             curWind = frontWind;
  413.             if (curPos.v + windHeight >= screenRect.bottom ||
  414.                 curPos.h + windWidth >= screenRect.right) {
  415.                 break;
  416.             };
  417.             nOccupied = 0;
  418.             while (curWind) {
  419.                 /* Scan the window list and count up how many of them "occupy"
  420.                     the current location curPos.  Break out of the loop when
  421.                     we reach the end of the list, or when the count is >=
  422.                     layer. */
  423.                 SetPt(&windPos, 0, 0);
  424.                 SetPort(curWind);
  425.                 LocalToGlobal(&windPos);
  426.                 deltaH = curPos.h - windPos.h;
  427.                 deltaV = curPos.v - windPos.v;
  428.                 if (deltaH < 0) deltaH = -deltaH;
  429.                 if (deltaV < 0) deltaV = -deltaV;
  430.                 if (deltaH <= offsetDiv2 && deltaV <= offsetDiv2) {
  431.                     nOccupied++;
  432.                     if (nOccupied >= layer) break;
  433.                 };
  434.                 curWind = (WindowPtr)(((WindowPeek)curWind)->nextWindow);
  435.             };
  436.             if (!curWind) break;
  437.             curPos.h += offset;
  438.             curPos.v += offset;
  439.         };
  440.         if (!curWind) break;
  441.         layer++;
  442.     };
  443.     SetPort(savedPort);
  444.     *pos = curPos;
  445. }
  446.  
  447. /*______________________________________________________________________
  448.  
  449.     utl_PlugParams - Plug parameters into message.
  450.     
  451.     Entry:    line1 = input line.
  452.                 p0, p1, p2, p3 = parameters.
  453.                     
  454.     Exit:        line2 = output line.
  455.                     
  456.     This routine works just like the toolbox routine ParamText.
  457.     The input line may contain place-holders ^0, ^1, ^2, and ^3, 
  458.     which are replaced by the parameters p0-p3.  The input line
  459.     must not contain any other ^ characters.  The input and output lines
  460.     may not be the same string.  Pass nil for parameters which don't
  461.     occur in line1.  If the output line exceeds 255 characters it's
  462.     truncated.
  463. _____________________________________________________________________*/
  464.  
  465.  
  466. void utl_PlugParams (Str255 line1, Str255 line2, Str255 p0, 
  467.     Str255 p1, Str255 p2, Str255 p3)
  468.  
  469. {
  470.     char                *in;            /* pointer to cur pos in input line */
  471.     char                *out;            /* pointer to cur pos in output line */
  472.     char                *inEnd;        /* pointer to end of input line */
  473.     char                *outEnd;        /* pointer to end of output line */
  474.     char                *param;        /* pointer to param to be plugged */
  475.     short                len;            /* length of param */
  476.     
  477.     in = line1+1;
  478.     out = line2+1;
  479.     inEnd = line1 + 1 + *line1;
  480.     outEnd = line2 + 256;
  481.     while (in < inEnd ) {
  482.         if (*in == '^') {
  483.             in++;
  484.             if (in >= inEnd) break;
  485.             switch (*in++) {
  486.                 case '0':
  487.                     param = p0;
  488.                     break;
  489.                 case '1':
  490.                     param = p1;
  491.                     break;
  492.                 case '2':
  493.                     param = p2;
  494.                     break;
  495.                 case '3':
  496.                     param = p3;
  497.                     break;
  498.                 default:
  499.                     continue;
  500.             };
  501.             if (!param) continue;
  502.             len = *param;
  503.             if (out + len > outEnd) len = outEnd - out;
  504.             memcpy(out, param+1, len);
  505.             out += len;
  506.         } else {
  507.             if (out >= outEnd) break;
  508.             *out++ = *in++;
  509.         };
  510.     };
  511.     *line2 = out - (line2+1);
  512. };
  513.  
  514. /*______________________________________________________________________
  515.  
  516.     utl_Rom64 - Check to see if we have the old 64K ROM.
  517.     
  518.     Exit:        function result = true if 64K ROM.
  519. _____________________________________________________________________*/
  520.  
  521.  
  522. Boolean utl_Rom64 (void)
  523.  
  524. {
  525.     return *(short*)ROM85 < 0;
  526. }
  527.  
  528. /*______________________________________________________________________
  529.  
  530.     utl_GetSysWD - Get WDRefNum of Blessed Folder.
  531.     
  532.     Exit:        function result = WDRefNum of Blessed Folder.
  533. _____________________________________________________________________*/
  534.  
  535.  
  536. short utl_GetSysWD (void)
  537.  
  538. {
  539.     if (!GotSysEnviron) GetSysEnvirons();
  540.     return TheWorld.sysVRefNum;
  541. }
  542.  
  543. /*______________________________________________________________________
  544.  
  545.     utl_CheckPack - Check to see if a package exists.
  546.     
  547.     Entry:    packNum = package number.
  548.                 preload = true to preload package.
  549.                     
  550.     Exit:        function result = true if package exists.
  551. _____________________________________________________________________*/
  552.  
  553.  
  554. Boolean utl_CheckPack (short packNum, Boolean preload)
  555.  
  556. {
  557.     short            trapNum;            /* trap number */
  558.     Handle        h;                    /* handle to PACK resource */
  559.     
  560.     /* Check to make sure the trap exists, by comparing its trap address to
  561.         the trap address of the unimplemented trap. */
  562.     
  563.     trapNum = packNum + 0x1e7;
  564.     if (NGetTrapAddress(trapNum, ToolTrap) == 
  565.         NGetTrapAddress(_Unimplemented, ToolTrap)) return false;
  566.         
  567.     /* Check to make sure the package exists on the System file or in 
  568.         ROM.  If it's not in ROM make it nonpurgeable, if requested. */
  569.     
  570.     if (preload) {
  571.         if (utl_Rom64()) {
  572.             h = GetResource('PACK', packNum);
  573.             if (!h) return false;
  574.             HNoPurge(h);
  575.         } else {
  576.             *(unsigned short*)RomMapInsert = 0xFF00;
  577.             h = GetResource('PACK', packNum);
  578.             if (!h) return false;
  579.             if ((*(unsigned long*)h & 0x00FFFFFF) < 
  580.                 *(unsigned long*)ROMBase) {
  581.                 h = GetResource('PACK', packNum);
  582.                 HNoPurge(h);
  583.             };
  584.         };
  585.         return true;
  586.     } else {
  587.         SetResLoad(false);
  588.         if (!utl_Rom64()) *(unsigned short*)RomMapInsert = 0xFF00;
  589.         h = GetResource('PACK', packNum);
  590.         SetResLoad(true);
  591.         if (h) return true; else return false;
  592.     };
  593. }
  594.  
  595. /*______________________________________________________________________
  596.  
  597.     utl_InitSpinCursor - Initialize animated cursor.
  598.     
  599.     Entry:    cursArray = array of handles to cursors.
  600.                 numCurs = number of cursors to rotate.
  601.                 tickInterval = interval between cursor rotations.
  602. _____________________________________________________________________*/
  603.  
  604.  
  605. void utl_InitSpinCursor (CursHandle *cursArray, short numCurs, 
  606.     short tickInterval)
  607.  
  608. {
  609.     CursHandle        h;
  610.  
  611.     CursArray = cursArray;
  612.     CurCurs = 0;
  613.     NumCurs = numCurs;
  614.     TickInterval = tickInterval;
  615.     LastTick = TickCount();
  616.     h = *cursArray;
  617.     SetCursor(*h);
  618. }
  619.  
  620.  
  621.  
  622. /*______________________________________________________________________
  623.  
  624.     utl_SpinCursor - Animate cursor.
  625.     
  626.     After calling InitSpinCursor to initialize an animated cursor, call
  627.     SpinCursor periodically to make the cursor animate.
  628. _____________________________________________________________________*/
  629.  
  630.  
  631. void utl_SpinCursor (void)
  632.  
  633. {
  634.     CursHandle        h;                /* handle to cursor */
  635.     long                ticksNow;    /* current tick count */
  636.     
  637.     ticksNow = TickCount();
  638.     if (ticksNow < LastTick + TickInterval) return;
  639.     LastTick = ticksNow;
  640.     CurCurs++;
  641.     if (CurCurs >= NumCurs) CurCurs = 0;
  642.     h = CursArray[CurCurs];
  643.     SetCursor(*h);
  644. }
  645.  
  646. /*______________________________________________________________________
  647.  
  648.     utl_VolIsMFS - Test for MFS volume.
  649.     
  650.     Entry:    vRefNum = volume reference number.
  651.     
  652.     Exit:        function result = true if volume is MFS.
  653. _____________________________________________________________________*/
  654.  
  655.  
  656. Boolean utl_VolIsMFS (short vRefNum)
  657.  
  658. {
  659.     HParamBlockRec        vBlock;            /* vol info param block */
  660.     
  661.     vBlock.volumeParam.ioNamePtr = nil;
  662.     vBlock.volumeParam.ioVolIndex = 0;
  663.     vBlock.volumeParam.ioVRefNum = vRefNum;
  664.     vBlock.volumeParam.ioVSigWord = 0xd2d7;    /* in case we don't have HFS */
  665.     (void) PBHGetVInfo(&vBlock, false);
  666.     return vBlock.volumeParam.ioVSigWord == 0xd2d7;
  667. }
  668.  
  669. /*______________________________________________________________________
  670.  
  671.     utl_Ejectable - Test for ejectable volume.
  672.     
  673.     Entry:    vRefNum = volume reference number.
  674.     
  675.     Exit:        function result = true if volume is on an ejectable drive.
  676. _____________________________________________________________________*/
  677.  
  678.  
  679. Boolean utl_Ejectable (short vRefNum)
  680.     
  681. {
  682.     HParamBlockRec    pBlock;                /* vol info param block */
  683.     short                driveNum;            /* driver number of cur vol */
  684.     DrvQEl            *curDrive;            /* ptr to current drive queue element */
  685.     OSErr                rCode;                /* result code */
  686.     unsigned char    flagByte;            /* drive queue element flag byte */
  687.     
  688.     /* Get driveNum = drive number of drive containing volume. */
  689.     
  690.     pBlock.volumeParam.ioNamePtr = nil;
  691.     pBlock.volumeParam.ioVolIndex = 0;
  692.     pBlock.volumeParam.ioVRefNum = vRefNum;;
  693.     if (rCode = PBHGetVInfo(&pBlock, false)) return false;
  694.     driveNum = pBlock.volumeParam.ioVDrvInfo;
  695.     
  696.     /*    Walk the drive queue until we find driveNum.  The second byte in
  697.         the four flag bytes preceding the drive queue element is 8 or $48 
  698.         if the drive is nonejectable. */
  699.     
  700.     curDrive = (DrvQEl*)(GetDrvQHdr())->qHead;
  701.     while (true) {
  702.         if (curDrive->dQDrive == driveNum) {
  703.             flagByte = *((Ptr)curDrive - 3);
  704.             return (flagByte != 8 && flagByte != 0x48);
  705.         };
  706.         curDrive = (DrvQEl*)curDrive->qLink;
  707.         if (!curDrive) return false;
  708.     };
  709. }
  710.  
  711. /*______________________________________________________________________
  712.  
  713.     utl_DoDiskInsert - Handle a disk inserted event.
  714.     
  715.     Entry:    message = message field from disk insertion event record
  716.                     = 16/MountVol return code, 16/drive number.
  717.     
  718.     Exit:        vRefNum = vol ref num of inserted volume.
  719.                 function result = error code.
  720.     
  721.     If MountVol returned an error code, the disk initialization package
  722.     is called to initialize the disk.
  723. _____________________________________________________________________*/
  724.  
  725.  
  726. OSErr utl_DoDiskInsert (long message, short *vRefNum)
  727.  
  728. {
  729.     OSErr                rCode;                /* result code */
  730.     short                driveNum;            /* drive number */
  731.     HParamBlockRec    pBlock;                /* vol info param block */
  732.     Handle            dlgHandle;            /* handle to disk init dialog */
  733.     Rect                dlgRect;                /* disk init dialog rectangle */
  734.     Point                where;                /* location of disk init dialog */
  735.     short                curVol;                /* index in VCB queue */
  736.     
  737.     /* Get result code and drive number from event message. */
  738.     
  739.     rCode = (message >> 16) & 0xffff;
  740.     driveNum = message & 0xffff;
  741.     
  742.     /* If the result code indicates an error, call DIBadMount to initialize
  743.         the disk. */
  744.         
  745.     if (rCode) {
  746.         
  747.         /* Center the disk initialization package dialog. */
  748.         
  749.         DILoad();
  750.         dlgHandle = GetResource('DLOG', -6047);
  751.         dlgRect = **(Rect**)dlgHandle;
  752.         utl_CenterDlogRect(&dlgRect, false);
  753.         SetPt(&where, dlgRect.left, dlgRect.top);
  754.         
  755.         /* Call DIBadMount. */
  756.         
  757.         if (rCode = DIBadMount(where, message)) return rCode;
  758.         
  759.     };
  760.     
  761.     /* Search mounted volumes to find inserted one. */
  762.     
  763.     pBlock.volumeParam.ioNamePtr = nil;
  764.     curVol = 0;
  765.     while (true) {
  766.         pBlock.volumeParam.ioVolIndex = ++curVol;
  767.         pBlock.volumeParam.ioVRefNum = 0;
  768.         if (rCode = PBHGetVInfo(&pBlock, false)) return rCode;
  769.         if (pBlock.volumeParam.ioVDrvInfo == driveNum) break;
  770.     };
  771.     *vRefNum = pBlock.volumeParam.ioVRefNum;
  772.     return noErr;
  773. }    
  774.  
  775. /*______________________________________________________________________
  776.  
  777.     utl_CopyPString - Copy Pascal String.
  778.     
  779.     Entry:    dest = destination string.
  780.                 source = source string.
  781. _____________________________________________________________________*/
  782.  
  783.  
  784. void utl_CopyPString (Str255 dest, Str255 source)
  785.  
  786. {
  787.     memcpy(dest, source, *source+1);
  788. }
  789.  
  790. /*______________________________________________________________________
  791.  
  792.     utl_GetNewWindow - Get New Window.
  793.     
  794.     Entry:    windowID = resource id of WIND resource.
  795.                 wStorage = pointer to window record.
  796.                 behind = window to insert in back of.
  797.                 
  798.     Exit:        function result = pointer to new window record.
  799.                 
  800.     This routine is identical to the Window Manager routine GetNewWindow,
  801.     except it does not release or make purgeable the WIND resource.
  802. _____________________________________________________________________*/
  803.  
  804.  
  805. WindowPtr utl_GetNewWindow (short windowID, Ptr wStorage, 
  806.     WindowPtr behind)
  807.     
  808. {
  809.     Rect            boundsRect;            /* boundary rectangle */
  810.     short            procID;                /* window proc id */
  811.     Boolean        visible;                /* true if visible */
  812.     Boolean        goAwayFlag;            /* true if window has go away box */
  813.     long            refCon;                /* refCon field for window record */
  814.     Str255        title;                /* window title */
  815.     Handle        theRez;                /* handle to WIND resource */
  816.     
  817.     theRez = GetResource('WIND', windowID);
  818.     boundsRect = *(Rect*)(*theRez);
  819.     procID = *(short*)(*theRez+8);
  820.     visible = *(Boolean*)(*theRez+10);
  821.     goAwayFlag = *(Boolean*)(*theRez+12);
  822.     refCon = *(long*)(*theRez+14);
  823.     utl_CopyPString(title, *theRez+18);
  824.     return NewWindow(wStorage, &boundsRect, title, visible, procID, behind,
  825.         goAwayFlag, refCon);
  826. }
  827.  
  828. /*______________________________________________________________________
  829.  
  830.     utl_GetNewDialog - Get New Dialog.
  831.     
  832.     Entry:    dialogID = resource id of DLOG resource.
  833.                 dStorage = pointer to dialog record.
  834.                 behind = window to insert in back of.
  835.                 
  836.     Exit:        function result = pointer to new dialog record.
  837.                 
  838.     This routine is identical to the Dialog Manager routine GetNewDialog,
  839.     except it does not release or make purgeable the DLOG resource.
  840. _____________________________________________________________________*/
  841.  
  842.  
  843. DialogPtr utl_GetNewDialog (short dialogID, Ptr dStorage, 
  844.     WindowPtr behind)
  845.     
  846. {
  847.     Rect            boundsRect;            /* boundary rectangle */
  848.     short            procID;                /* window proc id */
  849.     Boolean        visible;                /* true if visible */
  850.     Boolean        goAwayFlag;            /* true if window has go away box */
  851.     long            refCon;                /* refCon field for window record */
  852.     Str255        title;                /* window title */
  853.     Handle        theRez;                /* handle to DLOG resource */
  854.     short            itemID;                /* rsrc id of item list */
  855.     Handle        items;                /* handle to item list */
  856.     
  857.     theRez = GetResource('DLOG', dialogID);
  858.     boundsRect = *(Rect*)(*theRez);
  859.     procID = *(short*)(*theRez+8);
  860.     visible = *(Boolean*)(*theRez+10);
  861.     goAwayFlag = *(Boolean*)(*theRez+12);
  862.     refCon = *(long*)(*theRez+14);
  863.     itemID = *(short*)(*theRez+18);
  864.     utl_CopyPString(title, *theRez+20);
  865.     items = GetResource('DITL', itemID);
  866.     return NewDialog(dStorage, &boundsRect, title, visible, procID, behind,
  867.         goAwayFlag, refCon, items);
  868. }
  869.  
  870. /*______________________________________________________________________
  871.  
  872.     utl_GetNewControl - Get New Control.
  873.     
  874.     Entry:    controlID = resource id of CNTL resource.
  875.                 theWindow = pointer to window record.
  876.                 
  877.     Exit:        function result = handle to new control record.
  878.                 
  879.     This routine is identical to the Control Manager routine GetNewControl,
  880.     except it does not release or make purgeable the CNTL resource.
  881. _____________________________________________________________________*/
  882.  
  883.  
  884. ControlHandle utl_GetNewControl (short controlID, 
  885.     WindowPtr theWindow)
  886.     
  887. {
  888.     Rect            boundsRect;            /* boundary rectangle */
  889.     short            value;                /* initial control value */
  890.     Boolean        visible;                /* true if visible */
  891.     short            max;                    /* max control value */
  892.     short            min;                    /* min control value */
  893.     short            procID;                /* window proc id */
  894.     long            refCon;                /* refCon field for window record */
  895.     Str255        title;                /* window title */
  896.     Handle        theRez;                /* handle to CNTL resource */
  897.     
  898.     theRez = GetResource('CNTL', controlID);
  899.     boundsRect = *(Rect*)(*theRez);
  900.     value = *(short*)(*theRez+8);
  901.     visible = *(Boolean*)(*theRez+10);
  902.     max = *(short*)(*theRez+12);
  903.     min = *(short*)(*theRez+14);
  904.     procID = *(short*)(*theRez+16);
  905.     refCon = *(long*)(*theRez+18);
  906.     utl_CopyPString(title, *theRez+22);
  907.     return NewControl(theWindow, &boundsRect, title, visible, value,
  908.         min, max, procID, refCon);
  909. }
  910.  
  911. /*______________________________________________________________________
  912.  
  913.     utl_WaitNextEvent - Get Next Event.
  914.     
  915.     Entry:    eventMask = event mask.
  916.                 sleep = sleep interval.
  917.                 mouseRgn = mouse region.
  918.     
  919.     Exit:        theEvent = the next event.
  920.                 function result = true if event to be processed.
  921.                 
  922.     This routine calls WaitNextEvent if the trap exists, otherwise it
  923.     calls GetNextEvent.  
  924.     
  925.     If GetNextEvent is called, the sleep and mouseRgn parameters are 
  926.     ignored.  SystemTask is also called.
  927.                 
  928.     This routine also saves and restores the current grafport.  This is
  929.     necessary to protect against some GetNextEvent trap patches which change
  930.     the grafport without restoring it (e.g., the Flex screen saver).
  931. _____________________________________________________________________*/
  932.  
  933.  
  934. Boolean utl_WaitNextEvent (short eventMask, EventRecord *theEvent,
  935.     long sleep, RgnHandle mouseRgn)
  936.  
  937. {
  938.     GrafPtr            curPort;        /* pointer to current grafport */
  939.     Boolean            result;        /* function result */
  940.     static short    wne = 2;        /* 0 if WaitNextEvent does not exist
  941.                                             1 if WaitNextEvent exists
  942.                                             2 if we don't yet know (first call) */
  943.     
  944.     /* Find out whether the WaitNextEvent trap is implemented if this is 
  945.         the first call. */
  946.     
  947.     if (wne == 2) {
  948.         if (!GotSysEnviron) GetSysEnvirons();
  949.         if (TheWorld.machineType < 0) {
  950.             wne = false;
  951.         } else {
  952.             wne = (NGetTrapAddress(_WaitNextEvent, ToolTrap) == 
  953.                 NGetTrapAddress(_Unimplemented, ToolTrap)) ? 0 : 1;
  954.         };
  955.     };
  956.     
  957.     /* Save the port, call the trap, and restore the port. */
  958.     
  959.     GetPort(&curPort);
  960.     if (wne) {
  961.         result = WaitNextEvent(eventMask, theEvent, sleep, mouseRgn);
  962.     } else {
  963.         SystemTask();
  964.         result = GetNextEvent(eventMask, theEvent);
  965.     };
  966.     SetPort(curPort);
  967.     return result;
  968. }
  969.  
  970. /*______________________________________________________________________
  971.  
  972.     utl_DILoad - Load Disk Initialization Package.
  973.     
  974.     Exit:        Disk initialization package loaded.
  975.                 
  976.     This routine is identical to the DILoad routine (see IM II-396),
  977.     except that it closes any resource files opened by the routine.  This is
  978.     necessary to undo a bug in the DaynaFile software.  DaynaFile patches
  979.     DILoad.  The patch opens a resource file without closing it.  The
  980.     effect on Disinfectant if we don't do anything about this is that 
  981.     the DaynaFile icon is displayed in Disinfectant's main window instead of
  982.     Disinfectant's icon.  
  983. _____________________________________________________________________*/
  984.  
  985.  
  986. void utl_DILoad (void)
  987.  
  988. {
  989.     short            curResFile;            /* ref num of current resource file
  990.                                                 before calling DILoad */
  991.     short            topResFile;            /* ref num of top resource file
  992.                                                 after calling DILoad */
  993.     
  994.     curResFile = CurResFile();
  995.     DILoad();
  996.     while ((topResFile = CurResFile()) != curResFile) CloseResFile(topResFile);
  997. }
  998.  
  999. /*______________________________________________________________________
  1000.  
  1001.     CancelFilter - Command Period Dialog Filter Proc.
  1002.     
  1003.     Entry:    theDialog = pointer to dialog record.
  1004.                 theEvent = pointer to event record.
  1005.     
  1006.     Exit:        if command-period typed:
  1007.     
  1008.                 function result = true.
  1009.                 itemHit = item number of cancel button.
  1010.                 
  1011.                 else if user specified a filterProc on the call to
  1012.                 utl_StopAlert:
  1013.                 
  1014.                 user's filterProc called, function result and itemHit
  1015.                 returned by user's filterProc.
  1016.                 
  1017.                 else:
  1018.                 
  1019.                 function result = false.
  1020.                 itemHit = undefined.
  1021. _____________________________________________________________________*/
  1022.  
  1023.  
  1024. static pascal Boolean CancelFilter (DialogPtr theDialog,
  1025.     EventRecord *theEvent, short *itemHit)
  1026.     
  1027. {
  1028.     short                key;            /* ascii code of key pressed */
  1029.     
  1030.     key = theEvent->message & charCodeMask;
  1031.     if ((theEvent->modifiers & cmdKey) &&
  1032.         (key == '.')) {
  1033.         *itemHit = CancelItem;
  1034.         return true;
  1035.     } else if (Filter) {
  1036.         return (*Filter)(theDialog, theEvent, itemHit);
  1037.     } else if (key == returnKey || key==enterKey) {
  1038.         *itemHit = 1;
  1039.         return true;
  1040.     } else {
  1041.         return false;
  1042.     };
  1043. }
  1044.  
  1045. /*______________________________________________________________________
  1046.  
  1047.     utl_StopAlert - Present Stop Alert
  1048.     
  1049.     Entry:    alertID = resource id of alert.
  1050.                 filterProc = pointer to filter proc.
  1051.                 cancelItem = item number of cancel button, or 0 if
  1052.                     none.
  1053.     
  1054.     Exit:        function result = item number
  1055.                 
  1056.     This routine is identical to the Dialog Manager routine StopAlert,
  1057.     except that it centers the alert on the main window, and if requested,
  1058.     command/period is treated the same as a click on the Cancel button.
  1059. _____________________________________________________________________*/
  1060.  
  1061.  
  1062. short utl_StopAlert (short alertID, ModalFilterProcPtr filterProc,
  1063.     short cancelItem)
  1064.  
  1065. {
  1066.     Handle            h;                /* handle to alert resource */
  1067.     char                flags;        /* handle state flags */
  1068.     short                result;        /* function result */
  1069.     
  1070.     h = GetResource('ALRT', alertID);
  1071.     flags = HGetState(h);
  1072.     HNoPurge(h);
  1073.     utl_CenterDlogRect(*(Rect**)h, false);
  1074.     if (cancelItem) {
  1075.         Filter = filterProc;
  1076.         CancelItem = cancelItem;
  1077.         result = StopAlert(alertID, CancelFilter);
  1078.     } else {
  1079.         result = StopAlert(alertID, filterProc);
  1080.     };
  1081.     HSetState(h, flags);
  1082.     return result;
  1083. }
  1084.  
  1085. /*______________________________________________________________________
  1086.  
  1087.     utl_FixStdFile - Fix Standard File Pacakge.
  1088.     
  1089.     This routine should be called before calling the Standard File 
  1090.     package if there's any chance that SFSaveDisk might specify
  1091.     a volume that has been umounted.  Standard File gets confused if this
  1092.     happens and presents an alert telling the user that a "system error"
  1093.     has occurred.
  1094.     
  1095.     This routine checks to make sure that SFSaveDisk specifies a volume 
  1096.     that is still mounted.  If not, it sets it to the first mounted 
  1097.     volume, and it sets CurDirStore to the root directory on that volume.
  1098. _____________________________________________________________________*/
  1099.                     
  1100.                     
  1101. void utl_FixStdFile (void)
  1102.  
  1103. {
  1104.     ParamBlockRec    vBlock;            /* vol info param block */
  1105.                                                 
  1106.     vBlock.volumeParam.ioNamePtr = nil;
  1107.     vBlock.volumeParam.ioVRefNum = -*(short*)SFSaveDisk;
  1108.     vBlock.volumeParam.ioVolIndex = 0;
  1109.     if (PBGetVInfo(&vBlock, false)) {
  1110.         vBlock.volumeParam.ioVolIndex = 1;
  1111.         (void) PBGetVInfo(&vBlock, false);
  1112.         *(short*)SFSaveDisk = -vBlock.volumeParam.ioVRefNum;
  1113.         if (*(short*)FSFCBLen > 0) *(long*)CurDirStore = fsRtDirID;
  1114.     };
  1115. }
  1116.  
  1117. /*______________________________________________________________________
  1118.  
  1119.     utl_IsLaser - Check Printer for LaserWriter.
  1120.     
  1121.     Entry:    hPrint = handle to print record.
  1122.     
  1123.     Exit:        function result = true if LaserWriter.
  1124.     
  1125. _____________________________________________________________________*/
  1126.  
  1127.  
  1128. Boolean utl_IsLaser (THPrint hPrint)
  1129.  
  1130. {
  1131.     unsigned char    wDev;                /* printer device */
  1132.  
  1133.     wDev = (**hPrint).prStl.wDev >> 8;
  1134.     return wDev==3 || wDev==4;
  1135. }
  1136.  
  1137. /*______________________________________________________________________
  1138.  
  1139.     utl_AppendDITL - Append DITL to End of Dialog.
  1140.     
  1141.     Entry:    theDialog = pointer to dialog.
  1142.                 theDITLID = rsrc id of DITL.
  1143.                     
  1144.     Exit:        function result = item number of first appended item.
  1145.     
  1146.     The dialog window is expanded to accomodate the new items, and the
  1147.     new items are offset to appear at the bottom of the dialog.
  1148.     
  1149.     This routine is particularly useful for appending items to the
  1150.     standard Page Setup and Print Job dialogs.  (See TN 95).  It was
  1151.     written by Lew Rollins of Apple's Human-Systems Interface Group,
  1152.     in MPW Pascal.  I translated it to MPW C.
  1153.     
  1154.     The only significant difference between this routine and Rollin's
  1155.     version is that this version does not release the DITL resource.
  1156. _____________________________________________________________________*/
  1157.  
  1158.  
  1159. short utl_AppendDITL (DialogPtr theDialog, short theDITLID)
  1160.  
  1161. {
  1162.     typedef struct DITLItem {
  1163.         Handle            itmHndl;                /* handle or proc ptr */
  1164.         Rect                itmRect;                /* display rect */
  1165.         char                itmType;                /* item type */
  1166.         unsigned char    itmData;                /* item data length byte */
  1167.     } DITLItem;
  1168.     
  1169.     typedef struct itemList {
  1170.         short                dlgMaxIndex;        /* num items - 1 */
  1171.         DITLItem            DITLItems[1];        /* array of DITL items */
  1172.     } itemList;
  1173.     
  1174.     short                offset;            /* item offset */
  1175.     Rect                maxRect;            /* max dialog rect size so far */
  1176.     Handle            hDITL;            /* handle to DITL */
  1177.     DITLItem            *pItem;            /* pointer to item being appended */
  1178.     itemList            **hItems;        /* handle to DLOG's item list */
  1179.     short                sizeDITL;        /* size of DLOG's item list */
  1180.     short                firstItem;        /* item num of first appended item */
  1181.     short                newItems;        /* number of new items */
  1182.     short                dataSize;        /* size of data for current item */
  1183.     short                i;                    /* loop index */
  1184.     
  1185.     /* Initialize. */
  1186.     
  1187.     maxRect = theDialog->portRect;
  1188.     offset = maxRect.bottom;
  1189.     maxRect.bottom -= 5;
  1190.     maxRect.right -= 5;
  1191.     hItems = (itemList**)(((DialogPeek)theDialog)->items);
  1192.     sizeDITL = GetHandleSize((Handle)hItems);
  1193.     firstItem = (**hItems).dlgMaxIndex + 2;
  1194.     hDITL = GetResource('DITL', theDITLID);
  1195.     HLock(hDITL);
  1196.     newItems = **(short**)hDITL + 1;
  1197.     PtrAndHand(*hDITL+2, (Handle)hItems,
  1198.         GetHandleSize(hDITL)-2);
  1199.     (**hItems).dlgMaxIndex += newItems;
  1200.     HUnlock(hDITL);
  1201.     HLock((Handle)hItems);
  1202.     (char*)pItem = (char*)(*hItems) + sizeDITL;
  1203.     
  1204.     /* Main loop.  Add each item to dialog item list. */
  1205.     
  1206.     for (i = 1; i <= newItems; i++) {
  1207.         OffsetRect(&pItem->itmRect, 0, offset);
  1208.         UnionRect(&pItem->itmRect, &maxRect, &maxRect);
  1209.         switch (pItem->itmType & 0x7f) {
  1210.             case ctrlItem+btnCtrl:
  1211.             case ctrlItem+chkCtrl:
  1212.             case ctrlItem+radCtrl:
  1213.                 pItem->itmHndl = (Handle)NewControl(theDialog, 
  1214.                     &pItem->itmRect, &pItem->itmData, true, 0, 0, 1, 
  1215.                     pItem->itmType & 0x03, 0);
  1216.                 break;
  1217.             case ctrlItem+resCtrl:
  1218.                 pItem->itmHndl = (Handle)GetNewControl(
  1219.                     *(short*)(&pItem->itmData+1),
  1220.                     theDialog);
  1221.                 (**((ControlHandle)(pItem->itmHndl))).contrlRect = 
  1222.                     pItem->itmRect;
  1223.                 break;
  1224.             case statText:
  1225.             case editText:
  1226.                 PtrToHand(&pItem->itmData+1, &(Handle)(pItem->itmHndl), 
  1227.                     pItem->itmData);
  1228.                 break;
  1229.             case iconItem:
  1230.                 pItem->itmHndl = GetIcon(*(short*)(&pItem->itmData+1));
  1231.                 break;
  1232.             default:
  1233.                 pItem->itmHndl = nil;
  1234.         };
  1235.         dataSize = (pItem->itmData + 1) & 0xfffe;
  1236.         (char*)pItem += dataSize + sizeof(DITLItem);
  1237.     };
  1238.     
  1239.     /* Finish up. */
  1240.     
  1241.     HUnlock((Handle)hItems);
  1242.     maxRect.bottom += 5;
  1243.     maxRect.right += 5;
  1244.     SizeWindow(theDialog, maxRect.right, maxRect.bottom, true);
  1245.     return firstItem;
  1246. }
  1247.  
  1248. /*______________________________________________________________________
  1249.  
  1250.     utl_ScaleFontSize - Scale Font Size
  1251.     
  1252.     Entry:    fontNum = font number.
  1253.                 fontSize = nominal font size.
  1254.                 percent = percent change in size.
  1255.                 laser = true if laserwriter.
  1256.     
  1257.     Exit:        function result = scaled font size.
  1258.                 
  1259.     The nominal font size is multiplied by the percentage,
  1260.     then truncated.  For non-laserwriters it is then rounded down
  1261.     to the nearest font size which is available in that true size,
  1262.     without font manager scaling, or which can be generated by doubling
  1263.     an existing font size.
  1264. _____________________________________________________________________*/
  1265.  
  1266.  
  1267. short utl_ScaleFontSize (short fontNum, short fontSize, short percent,
  1268.     Boolean laser)
  1269.     
  1270. {
  1271.     short            nSize;                /* new size */
  1272.     short            x;                        /* new test size */
  1273.     
  1274.     nSize = fontSize * percent / 100;
  1275.     if (!laser) {
  1276.         x = nSize;
  1277.         while (x > 0) {
  1278.             if (RealFont(fontNum, x)) break;
  1279.             if (!(x&1) && RealFont(fontNum, x>>1)) break;
  1280.             x--;
  1281.         };
  1282.         if (x) nSize = x;
  1283.     };
  1284.     return nSize;
  1285. }
  1286.  
  1287. /*______________________________________________________________________
  1288.  
  1289.     utl_GetFontNumber - Get Font Number.
  1290.     
  1291.     Entry:    fontName = font name.
  1292.     
  1293.     Exit:        function result = true if font exists.
  1294.                 fontNum = font number.
  1295.                 
  1296.     Copied from TN 191.
  1297. _____________________________________________________________________*/
  1298.  
  1299.  
  1300. Boolean utl_GetFontNumber (Str255 fontName, short *fontNum)
  1301.  
  1302. {
  1303.     Str255        systemFontName;
  1304.     
  1305.     GetFNum(fontName, fontNum);
  1306.     if (*fontNum) {
  1307.         return true;
  1308.     } else {
  1309.         GetFontName(0, systemFontName);
  1310.         return EqualString(fontName, systemFontName, false, false);
  1311.     };
  1312. }
  1313.  
  1314. /*______________________________________________________________________
  1315.  
  1316.     utl_DrawGrowIcon - Draw Grow Icon.
  1317.     
  1318.     Entry:            theWindow = pointer to window.
  1319.     
  1320.     This routine is identical to the Window Manager routine 
  1321.     DrawGrowIcon, except that it does not draw the lines enclosing the
  1322.     scroll bars.
  1323. _____________________________________________________________________*/
  1324.  
  1325.  
  1326. void utl_DrawGrowIcon (WindowPtr theWindow) 
  1327.  
  1328. {
  1329.     RgnHandle            clipRgn;            /* saved clip region */
  1330.     Rect                    clipRect;        /* clip rectangle */
  1331.     
  1332.     clipRgn = NewRgn();
  1333.     GetClip(clipRgn);
  1334.     clipRect = theWindow->portRect;
  1335.     clipRect.left = clipRect.right - 15;
  1336.     clipRect.top = clipRect.bottom - 15;
  1337.     ClipRect(&clipRect);
  1338.     DrawGrowIcon(theWindow);
  1339.     SetClip(clipRgn);
  1340.     DisposeRgn(clipRgn);
  1341. }
  1342.  
  1343. /*______________________________________________________________________
  1344.  
  1345.     utl_InvalGrow - Invalidate Grow Icon.
  1346.     
  1347.     Entry:            theWindow = pointer to window.
  1348.     
  1349.     This routine should be called before and after calling SizeWindow
  1350.     for windows with grow icons.
  1351. _____________________________________________________________________*/
  1352.  
  1353.  
  1354. void utl_InvalGrow (WindowPtr theWindow)
  1355.  
  1356. {
  1357.     Rect            r;            /* rect to be invalidated */
  1358.     
  1359.     r = theWindow->portRect;
  1360.     r.top = r.bottom - 15;
  1361.     r.left = r.right - 15;
  1362.     InvalRect(&r);
  1363. };
  1364.  
  1365. /*______________________________________________________________________
  1366.  
  1367.     utl_GetLongSleep - Get Long Sleep Time.
  1368.     
  1369.     Exit:            function result = long sleep time.
  1370.     
  1371.     Returns the largest positive long integer (0x7fffffff) if the 
  1372.     system version is > 0x04ff, else returns 50.  See TN 177.
  1373. _____________________________________________________________________*/
  1374.  
  1375.  
  1376. long utl_GetLongSleep (void)
  1377.  
  1378. {
  1379.     if (!GotSysEnviron) GetSysEnvirons();
  1380.     return (TheWorld.systemVersion > 0x04ff) ? 0x7fffffff : 50;
  1381. }
  1382.  
  1383. /*______________________________________________________________________
  1384.  
  1385.     utl_SysHasPopUp - Check to See if System has Popup Menus.
  1386.     
  1387.     Exit:            function result = true if system has popup menus.
  1388.     
  1389.     The system version must be >= 4.1, the machine must have the 128 ROM or 
  1390.     later, and the PopUpMenuSelect trap must exist.
  1391. _____________________________________________________________________*/
  1392.  
  1393.  
  1394. Boolean utl_SysHasPopUp (void)
  1395.  
  1396. {
  1397.     if (!GotSysEnviron) GetSysEnvirons();
  1398.     if ((TheWorld.systemVersion < 0x0410) || (TheWorld.machineType == envMac)) {
  1399.         return false;
  1400.     } else {
  1401.         return NGetTrapAddress(_PopUpMenuSelect, ToolTrap) !=
  1402.             NGetTrapAddress(_Unimplemented, ToolTrap);
  1403.     };
  1404. }
  1405.  
  1406. /*______________________________________________________________________
  1407.  
  1408.     utl_CouldDrag - Determine if a window could be dragged to a location.
  1409.     
  1410.     Entry:    windRect = window rectangle, in global coords.
  1411.                 offset = pixel offset used in DragRect calls.
  1412.     
  1413.     Exit:        function result = true if the window could have been
  1414.                     dragged to the specified position.
  1415.                     
  1416.     This routine is used when restoring windows to saved positions.  According
  1417.     to HIN 6, we must check to see if the window "could have been dragged to
  1418.     the saved position."
  1419.     
  1420.     The "offset" parameter is usually 4.  When initializing the boundary rectangle
  1421.     for DragWindow calls, normally the boundary rectangle of the desktop gray
  1422.     region is inset by 4 pixels.  If some value other than 4 is used, it should
  1423.     be passed to CouldDrag as the "offset" parameter.
  1424.     
  1425.     The algorithm used is the following:  The routine computes the four squares
  1426.     at the corners of the title bar.  "true" is returned if and only if at least one 
  1427.     of these four squares is completely contained within the desktop gray region.
  1428.     
  1429.     Three pixels are added to the offset to err on the side of requiring a larger
  1430.     portion of the drag bar to be visible.  
  1431. _____________________________________________________________________*/
  1432.  
  1433.  
  1434. Boolean utl_CouldDrag (Rect *windRect, short offset)
  1435.  
  1436. {
  1437.     RgnHandle            rgn;            /* scratch region handle */
  1438.     Boolean                could;        /* function result */
  1439.     short                    corner;        /* which corner */
  1440.     Rect                    r;                /* corner rectangle */
  1441.  
  1442.     rgn = NewRgn();
  1443.     could = false;
  1444.     offset += 3;
  1445.     for (corner = 1; corner <= 4; corner++) {
  1446.         switch (corner) {
  1447.             case 1:
  1448.                 r.top = windRect->top - titleBarHeight;
  1449.                 r.left = windRect->left;
  1450.                 break;
  1451.             case 2:
  1452.                 r.top = windRect->top - offset;
  1453.                 r.left = windRect->left;
  1454.                 break;
  1455.             case 3:
  1456.                 r.top = windRect->top - titleBarHeight;
  1457.                 r.left = windRect->right - offset;
  1458.                 break;
  1459.             case 4:
  1460.                 r.top = windRect->top - offset;
  1461.                 r.left = windRect->right - offset;
  1462.                 break;
  1463.         };
  1464.         r.bottom = r.top + offset;
  1465.         r.right = r.left + offset;
  1466.         RectRgn(rgn, &r);
  1467.         DiffRgn(rgn, *(RgnHandle*)GrayRgn, rgn);
  1468.         if (EmptyRgn(rgn)) {
  1469.             could = true;
  1470.             break;
  1471.         };
  1472.     };
  1473.     DisposeRgn(rgn);
  1474.     return could;
  1475. }
  1476.  
  1477. /*______________________________________________________________________
  1478.  
  1479.     utl_SaveWindowPos - Save Window Position.
  1480.     
  1481.     Entry:    theWindow = window pointer.
  1482.     
  1483.     Exit:        userState = user state rectangle of the window.
  1484.                 zoomed = true if window zoomed.
  1485.                 
  1486.     See HIN 6: "Before closing a movable window, check to see if its
  1487.     location or size have changed.  If so, save the new location and
  1488.     size.  If the window can be zoomed, save the user state and also 
  1489.     save whether or not the window is in the zoomed (standard) sate."
  1490.     
  1491.     We assume in this routine that the caller has already kept track
  1492.     of the fact that this window's location or size has changed, and that
  1493.     we do indeed need to save the location and size.
  1494.     
  1495.     This routine only works if the window's origin has not been offset.
  1496. _____________________________________________________________________*/
  1497.  
  1498.  
  1499. void utl_SaveWindowPos (WindowPtr theWindow, Rect *userState, Boolean *zoomed)
  1500.  
  1501. {
  1502.     GrafPtr        savedPort;        /* saved grafport */
  1503.     WindowPeek    w;                    /* window pointer */
  1504.     Rect            curState;        /* current window rect, global coords */
  1505.     Rect            stdState;        /* standard (zoom) rect, global coords */
  1506.     Point            p;                    /* scratch point */
  1507.     Rect            r;                    /* scratch rect */
  1508.     
  1509.     GetPort(&savedPort);
  1510.     SetPort(theWindow);
  1511.     SetPt(&p, 0, 0);
  1512.     LocalToGlobal(&p);
  1513.     curState = theWindow->portRect;
  1514.     OffsetRect(&curState, p.h, p.v);
  1515.     w = (WindowPeek)theWindow;
  1516.     if (w->dataHandle && w->spareFlag) {
  1517.         /* This window supports zooming */
  1518.         /* Determine if window is zoomed.  The criteria is that both the
  1519.             top left and bottom right corners of the current window rectangle
  1520.             and the standard (zoom) rectangle must be within 7 pixels of each
  1521.             other.  This is the same algorithm as the one used by the standard
  1522.             system window definition function. */
  1523.         *zoomed = false;
  1524.         stdState = (**((WStateData**)w->dataHandle)).stdState;
  1525.         SetPt(&p, curState.left, curState.top);
  1526.         SetRect(&r, stdState.left, stdState.top, stdState.left, stdState.top);
  1527.         InsetRect(&r, -7, -7);
  1528.         if (PtInRect(p, &r)) {
  1529.             SetPt(&p, curState.right, curState.bottom);
  1530.             SetRect(&r, stdState.right, stdState.bottom, stdState.right,
  1531.                 stdState.bottom);
  1532.             InsetRect(&r, -7, -7);
  1533.             *zoomed = PtInRect(p, &r);
  1534.         };
  1535.         if (*zoomed) {
  1536.             *userState = (**((WStateData**)w->dataHandle)).userState;
  1537.         } else {
  1538.             *userState = curState;
  1539.         };
  1540.     } else {
  1541.         /* This window does not support zooming. */
  1542.         *zoomed = false;
  1543.         *userState = curState;
  1544.     };
  1545.     SetPort(savedPort);
  1546. }
  1547.  
  1548. /*______________________________________________________________________
  1549.  
  1550.     utl_RestoreWindowPos - Restore Window Position.
  1551.     
  1552.     Entry:    theWindow = pointer to window.
  1553.                 userState = saved user state rectangle for the window.
  1554.                 zoomed = true if window in zoomed state when saved.
  1555.                 offset = pixel offset used in DragRect calls.
  1556.                 computeStdState = pointer to function to compute standard state.
  1557.                 computeDefState = pointer to function to compute default state.
  1558.     
  1559.     Exit:        window position, size, and zoom state restored.
  1560.                 userState = new user state.
  1561.                 
  1562.     See HIN 6: "When reopening a movable window, check its saved 
  1563.     position.  If the window is in a position to which the user could
  1564.     have dragged it, then leave it there.  If the window can be zoomed
  1565.     and was in the zoomed state when it was last closed, put it in the
  1566.     zoomed state again.  (Note that the current and previous zoomed states
  1567.     are not necessarily the same, since the window may be reopened on a
  1568.     different monitor.)  If the window is not in a position to which the
  1569.     user could have dragged it, then it must be relocated, so use the
  1570.     default location.  However, do not automatically use the default size
  1571.     when using the default location; if the entire window would be visible
  1572.     using the default location and stored size, then use the stored size."
  1573.     
  1574.     The "offset" parameter is usually 4.  When initializing the boundary rectangle
  1575.     for DragWindow calls, normally the boundary rectangle of the desktop gray
  1576.     region is inset by 4 pixels.  If some value other than 4 is used, it should
  1577.     be passed to RestoreWindowPos as the "offset" parameter.
  1578.     
  1579.     The computeStdState function is passed a pointer to the window.  Given
  1580.     the userState in the window zoom info, it must compute the standard
  1581.     (zoom) state in the window zoom info.  This is an application-dependent
  1582.     function.
  1583.     
  1584.     The computeDefState function must determine the default position and
  1585.     size of a new window, and return the result as a rectangle.  This may
  1586.     involve invocation of a staggering algorithm or some other algorithm.
  1587.     This is an application-dependent function.
  1588. _____________________________________________________________________*/
  1589.  
  1590.  
  1591. void utl_RestoreWindowPos (WindowPtr theWindow, Rect *userState, 
  1592.     Boolean zoomed, short offset,
  1593.     utl_ComputeStdStatePtr computeStdState,
  1594.     utl_ComputeDefStatePtr computeDefState)
  1595.  
  1596. {
  1597.     WindowPeek        w;                    /* window pointer */
  1598.     short                userHeight;        /* height of userState */
  1599.     short                userWidth;        /* width of userState */
  1600.     Rect                r;                    /* scratch rectangle */
  1601.     RgnHandle        rgn;                /* scratch region */
  1602.     Rect                stdState;        /* standard state */
  1603.     short                windHeight;        /* window height */
  1604.     short                windWidth;        /* window width */
  1605.  
  1606.     w = (WindowPeek)theWindow;
  1607.     if (!utl_CouldDrag(userState, offset)) {
  1608.         userHeight = userState->bottom - userState->top;
  1609.         userWidth = userState->right - userState->left;
  1610.         (*computeDefState)(theWindow, userState);
  1611.         if (!zoomed) {
  1612.             r = *userState;
  1613.             r.bottom = r.top + userHeight;
  1614.             r.right = r.left + userWidth;
  1615.             r.top -= titleBarHeight;
  1616.             InsetRect(&r, -1, -1);
  1617.             rgn = NewRgn();
  1618.             RectRgn(rgn, &r);
  1619.             DiffRgn(rgn, *(RgnHandle*)GrayRgn, rgn);
  1620.             if (EmptyRgn(rgn)) {
  1621.                 userState->bottom = userState->top + userHeight;
  1622.                 userState->right = userState->left + userWidth;
  1623.             };
  1624.             DisposeRgn(rgn);
  1625.         };
  1626.     };
  1627.     if (w->dataHandle && w->spareFlag) {
  1628.         (**((WStateData**)w->dataHandle)).userState = *userState;
  1629.         (*computeStdState)(theWindow);
  1630.         if (zoomed) {
  1631.             stdState = (**((WStateData**)w->dataHandle)).stdState;
  1632.             MoveWindow(theWindow, stdState.left, stdState.top, false);
  1633.             windHeight = stdState.bottom - stdState.top;
  1634.             windWidth = stdState.right - stdState.left;
  1635.         };
  1636.     } else {
  1637.         zoomed = false;
  1638.     };
  1639.     if (!zoomed) {
  1640.         MoveWindow(theWindow, userState->left, userState->top, false);
  1641.         windHeight = userState->bottom - userState->top;
  1642.         windWidth = userState->right - userState->left;
  1643.     };
  1644.     SizeWindow(theWindow, windWidth, windHeight, true);
  1645. }
  1646.  
  1647. /*______________________________________________________________________
  1648.  
  1649.     utl_FrameItem
  1650.     
  1651.     Entry:    theWindow = pointer to dialog window.
  1652.                 itemNo = dialog item number.
  1653.     
  1654.     Exit:        dialog item rectangle framed.
  1655.                 
  1656.     This function is for use as a Dialog Manager user item procedure.
  1657.     It is particularly useful for drawing rules (straight lines).  Simply
  1658.     define the user item rectangle with bottom=top+1 or right=left+1.
  1659. _____________________________________________________________________*/
  1660.  
  1661.  
  1662. pascal void utl_FrameItem (WindowPtr theWindow, short itemNo)
  1663.  
  1664. {
  1665.     short            itemType;            /* item type */
  1666.     Handle        item;                    /* item handle */
  1667.     Rect            box;                    /* item rectangle */
  1668.  
  1669.     GetDItem(theWindow, itemNo, &itemType, &item, &box);
  1670.     FrameRect(&box);
  1671. }
  1672.  
  1673. /*______________________________________________________________________
  1674.  
  1675.     utl_IsDAWindow - Check to see if a window is a DA.
  1676.     
  1677.     Entry:    theWindow = pointer to dialog window.
  1678.                 
  1679.     
  1680.     Exit:        function result = true if DA window.
  1681. _____________________________________________________________________*/
  1682.  
  1683.  
  1684. Boolean utl_IsDAWindow (WindowPtr theWindow)
  1685.  
  1686. {
  1687.     return ((WindowPeek)theWindow)->windowKind < 0;
  1688. }
  1689.  
  1690. /*______________________________________________________________________
  1691.  
  1692.     utl_SysHasNotMgr - Check to See if System has Notification Manager.
  1693.     
  1694.     Exit:            function result = true if system has Notification
  1695.                         Manager..
  1696.     
  1697.     The system version must be >= 6.0.
  1698. _____________________________________________________________________*/
  1699.  
  1700.  
  1701. Boolean utl_SysHasNotMgr (void)
  1702.  
  1703. {
  1704.     if (!GotSysEnviron) GetSysEnvirons();
  1705.     return TheWorld.systemVersion >= 0x0600;
  1706. }
  1707.